package weekMatch.one_349;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class LeeCode_02 {
    public static void main(String[] args) {
        System.out.println(smallestString("cbabc"));
        System.out.println(smallestString("acbbc"));
        System.out.println(smallestString("leetcode"));
        System.out.println(smallestString("aa"));
        System.out.println(smallestString("ba"));
        System.out.println(smallestString("baa"));
    }

    private static String smallestString(String s) {
        String[] sons = s.split("a");
        StringBuilder sb = new StringBuilder();
        if (sons.length == 0) {
            sb.append(s);
            sb.replace(sb.length() - 1, sb.length(), "z");
            return sb.toString();
        }
        boolean flag = true;
        for (String son : sons) {
            if (son.length() == 0) {
                sb.append('a');
                continue;
            }
            if (flag) {
                StringBuilder sb2 = new StringBuilder();
                for (int i = 0; i < son.length(); i++) {
                    sb2.append((char) (son.charAt(i) - 1));
                }
                sb.append(sb2);
                flag = false;
            } else {
                sb.append(son);
            }
            sb.append('a');
        }
        sb.replace(sb.length() - 1, sb.length(), "");
        int count = 0;
        for (int i = s.length() - 1; i > 0; i--) {
            if (s.charAt(i) != 'a')
                break;
            count++;
        }
        for (int i = 0; i < count; i++) {
            sb.append('a');
        }
        return sb.toString();
    }
}